package com.company.aicrawlers.controller.api;

import com.company.aicrawlers.common.dto.ApiResponse;
import com.company.aicrawlers.common.exception.BusinessException;
import com.company.aicrawlers.entity.Product;
import com.company.aicrawlers.entity.ProductCompetitor;
import com.company.aicrawlers.service.ProductCompetitorService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 产品-竞品关联API控制器
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Slf4j
@RestController
@RequestMapping("/api/products")
public class ProductCompetitorApiController {
    
    @Autowired
    private ProductCompetitorService productCompetitorService;
    
    /**
     * 获取我方产品的竞品列表
     * 
     * 接口：GET /api/products/{id}/competitors
     *
     * @param id 我方产品ID
     * @param competitorType 竞争类型（可选）
     * @param strength 竞争强度（可选）
     * @return 竞品列表
     */
    @GetMapping(value = "/{id}/competitors", name = "getProductCompetitors")
    public ApiResponse<List<Product>> getCompetitors(
            @PathVariable("id") Long id,
            @RequestParam(required = false) String competitorType,
            @RequestParam(required = false) String strength
    ) {
        log.info("获取产品竞品，产品ID: {}, 类型: {}, 强度: {}", id, competitorType, strength);
        
        List<Product> competitors = productCompetitorService.getCompetitors(id, competitorType, strength);
        return ApiResponse.success(competitors);
    }
    
    /**
     * 添加产品-竞品关联
     * 
     * 接口：POST /api/products/{id}/competitors
     *
     * @param id 我方产品ID
     * @param relation 竞品关联对象
     * @return 关联ID
     */
    @PostMapping(value = "/{id}/competitors", name = "addProductCompetitor")
    public ApiResponse<Long> addCompetitor(
            @PathVariable("id") Long id,
            @RequestBody ProductCompetitor relation
    ) {
        log.info("添加竞品关联，我方产品ID: {}, 竞品ID: {}", id, relation.getCompetitorProductId());
        
        Long relationId = productCompetitorService.addCompetitorRelation(
                id,
                relation.getCompetitorProductId(),
                relation.getCompetitorType(),
                relation.getStrength(),
                relation.getDimension(),
                relation.getSortOrder(),
                relation.getRemark()
        );
        
        return ApiResponse.success(relationId, "添加竞品关联成功");
    }
    
    /**
     * 批量配置产品的竞品
     * 
     * 接口：PUT /api/products/{id}/competitors/batch
     *
     * @param id 我方产品ID
     * @param competitors 竞品配置列表
     * @return 成功消息
     */
    @PutMapping(value = "/{id}/competitors/batch", name = "batchConfigCompetitors")
    public ApiResponse<Void> batchConfigCompetitors(
            @PathVariable("id") Long id,
            @RequestBody List<ProductCompetitor> competitors
    ) {
        log.info("批量配置竞品，我方产品ID: {}, 竞品数量: {}", id, competitors.size());
        
        productCompetitorService.batchConfigCompetitors(id, competitors);
        return ApiResponse.success("批量配置成功");
    }
    
    /**
     * 移除产品-竞品关联
     * 
     * 接口：DELETE /api/products/{id}/competitors/{competitorId}
     *
     * @param id 我方产品ID
     * @param competitorId 竞品ID
     * @return 成功消息
     */
    @DeleteMapping(value = "/{id}/competitors/{competitorId}", name = "removeProductCompetitor")
    public ApiResponse<Void> removeCompetitor(
            @PathVariable("id") Long id,
            @PathVariable("competitorId") Long competitorId
    ) {
        log.info("移除竞品关联，我方产品ID: {}, 竞品ID: {}", id, competitorId);
        
        productCompetitorService.removeCompetitorRelation(id, competitorId);
        return ApiResponse.success("移除成功");
    }
    
    /**
     * 更新竞品关联信息
     * 
     * 接口：PUT /api/products/{id}/competitors/{competitorId}
     *
     * @param id 我方产品ID
     * @param competitorId 竞品ID
     * @param relation 竞品关联对象
     * @return 成功消息
     */
    @PutMapping(value = "/{id}/competitors/{competitorId}", name = "updateProductCompetitor")
    public ApiResponse<Void> updateCompetitor(
            @PathVariable("id") Long id,
            @PathVariable("competitorId") Long competitorId,
            @RequestBody ProductCompetitor relation
    ) {
        log.info("更新竞品关联，我方产品ID: {}, 竞品ID: {}", id, competitorId);
        
        // 获取现有关联
        ProductCompetitor exist = productCompetitorService.getRelation(id, competitorId);
        if (exist == null) {
            throw new BusinessException("竞品关联不存在");
        }
        
        // 更新字段
        exist.setCompetitorType(relation.getCompetitorType());
        exist.setStrength(relation.getStrength());
        exist.setDimension(relation.getDimension());
        exist.setSortOrder(relation.getSortOrder());
        exist.setRemark(relation.getRemark());
        
        productCompetitorService.updateRelation(exist);
        return ApiResponse.success("更新成功");
    }
    
    /**
     * 查询哪些我方产品将该竞品作为竞争对手（反向查询）
     * 
     * 接口：GET /api/products/competitor/{competitorId}/our-products
     *
     * @param competitorId 竞品ID
     * @return 我方产品列表
     */
    @GetMapping(value = "/competitor/{competitorId}/our-products", name = "getOurProductsByCompetitor")
    public ApiResponse<List<Product>> getOurProductsByCompetitor(@PathVariable("competitorId") Long competitorId) {
        log.info("查询竞品被哪些我方产品关注，竞品ID: {}", competitorId);
        
        List<Product> ourProducts = productCompetitorService.getOurProductsByCompetitor(competitorId);
        return ApiResponse.success(ourProducts);
    }
}

